package com.fzrskj.cloud.free.core.tool;

import java.io.*;
import java.net.Socket;

/**
 * CSocketRequestTool.
 *
 * @author zj.
 *         Created on 2018/9/13 0013.
 */
final public class CSocketRequestTool {
    /**
     * socket 通信.
     * @param xml
     * @param address
     * @param port
     * @return
     * @throws IOException
     */
    public String create(String xml ,String address,int port) throws IOException {
        Socket socket = null;
        Writer writer = null;
        BufferedReader br = null;
        String OutEncode = "UTF-8";
        String InEncode = "GB2312";
        String str = null;
        try{
            socket = new Socket(address,port);
            writer = new OutputStreamWriter(socket.getOutputStream(), OutEncode);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(),InEncode));
            writer.write(xml);
            writer.flush();
            StringBuffer buf;
            String line;

            buf = new StringBuffer();
            while((line = br.readLine()) != null)
            {
                buf.append(line);
                if (line.trim().endsWith("</boot>"))
                    break;
            }
            str = buf.toString();
        }catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }finally{
            if(writer!=null){
                writer.flush();
                writer.close();
            }
            if(br!=null)
                br.close();
            if(socket!=null)
                socket.close();
        }
        return str;
    }
}
